package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Session;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//客户
@RestController
@Slf4j
public class UserController {
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private HttpSession Session;
    //发送短信验证
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String,String> map){
        //接收参数
        String phone = map.get("phone");
        //生成验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "990122";
        log.info("生成的验证码是：{}",code);
        //保存session中
        httpSession.setAttribute("SMS_"+phone, code);
        //smsTemplate.sendSms(phone, code);
        return ResultInfo.success(null);
    }
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1.接收参数code phone
        String phone = map.get("phone");
        String code = map.get("code");
        //2.校验code对比前端传入的session中保存的，失败返回错误提示
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession)
        || StringUtils.isEmpty(code)
        || StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码错误");
        }
        //根据iPhone查询
        User user = userService.findByPhone(phone);
        if (user!=null){

        }else {
            User user1 = new User();
            user1.setPhone(phone);
            user1.setStatus(1);//激活
            userService.save(user);
        }
        //将user保存到session中
        httpSession.setAttribute("SESSION_USER", user);
        //返回成功消息
        return ResultInfo.success(user);
    }
    //查询列表
    @GetMapping("/category/list")
    public ResultInfo findList(){
        List<Category> categoryList = categoryService.findAll();
        return ResultInfo.success(categoryList);
    }
    @PostMapping("/user/logout")
    public ResultInfo logout(){
        Session.invalidate();
        return ResultInfo.success(null);
    }
    
}
